<template>
    <section class="goods-add-box">
        <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="80px">
            <!-- 商品信息 -->
            <el-card class="form-card">
                <div slot="header" class="add-title">商品信息</div>
                <el-form-item label="商品名称" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品品牌" prop="brand_id">
                    <el-select class="form-item-w" v-model="formData.brand_id" placeholder="请选择商品品牌">
                        <el-option
                            v-for="item in brandOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                    </el-select>
                    <el-button @click.stop='addBrand'>添加</el-button>
                </el-form-item>
                <el-form-item label="商品分类" prop="category_id">
                    <el-cascader
                    class="form-item-w"
                    v-model="formData.category_id"
                    :props="categoryProps"
                    :options="categoryOption"></el-cascader>
                    <el-button @click.stop="addCategory">添加</el-button>  
                </el-form-item>
                <el-form-item label="缩略图" prop="img">
                    <div class="upload-box _display_flex">
                        <div class="upload-item">
                            <div class="avatar-uploader avatar _display_flex" @click="handleUpload">
                                <img v-if="formData.img" :src="path + formData.img" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon avatar"></i>
                            </div>
                            <i class="upload-tab">【点击更换图片】</i>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="轮播图" prop="imgs">
                    <div class="upload-box _display_flex" >
                        <div class="upload-item _display_flex" v-for="(item, i) in switchImageUrlArr" :key="i" @click="handleSwitchSuccess(i)">
                            <div class="avatar-uploader avatar _display_flex">
                                <img v-if="item.img_path" :src="path + item.img_path" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon avatar"></i>
                                <div v-if="item.img_path" class="upload-del avatar _display_flex" @click.stop="handleSwitchRemove(i)">
                                    <i class="el-icon-delete "></i>
                                </div>
                            </div>
                            <i class="upload-tab">【点击更换图片】</i>
                        </div>
                    </div>
                </el-form-item>
            </el-card>
            <!-- 价格/规格/库存 -->
            <el-card class="form-card">
                <div slot="header" class="add-title">价格/规格/库存</div>
                <el-form-item label="销售价" prop="sales_price">
                    <el-input class="form-item-w" @input="onPriceInput(formData.sales_price, 'sales_price')" v-model="formData.sales_price"  placeholder="请输入销售价"></el-input>
                </el-form-item>
                <el-form-item label="活动价" prop="price">
                    <el-input class="form-item-w" @input="onPriceInput(formData.price, 'price')" v-model="formData.price"  placeholder="请输入活动价"></el-input>
                </el-form-item>
                <el-form-item label="折扣" prop="discount">
                    <el-input class="form-item-w" @input="onDiscountInput" v-model="formData.discount" placeholder="请输入折扣"></el-input>
                </el-form-item>
                <el-form-item label="总库存" prop="inventory">
                    <el-input class="form-item-w" @input="onIntegerInput"  v-model="formData.inventory" placeholder="请输入库存"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="serial_number" >
                    <el-input class="form-item-w" v-model="formData.serial_number" placeholder="请输入编号"></el-input>
                </el-form-item>
                <el-form-item label="属性">
                    <label slot="label" class="form-item-label">属性</label>
                    <el-input class="form-item-w" v-model="attributeName"  placeholder="请输入属性名称"></el-input>
                    <el-button type="success" size="small" @click="addAttribute">添加属性</el-button>
                </el-form-item>
                <!-- 属性值 -->
                <el-form-item :label="item.name" v-for="(item, index) in formData.attributeList" :key="index">
                    <div class="form-item-key">
                        <el-input class="form-item-w" v-model="item.value"  placeholder="请输入属性值"></el-input>
                        <el-button type="success" size="small" @click="addAttributeValue(index)">添加属性值</el-button>
                        <el-button type="danger" size="small" @click="delAttribute(index)">删除属性</el-button>
                    </div>
                    <div class="form-item-value _display_flex" v-for="(col, i) in item.children" :key="i">
                        <el-tag type="info" class="form-item-w">
                            <label>属性值：{{col}}</label>
                        </el-tag>
                        <i class="el-icon-remove-outline item-value-icon" @click="delAttributeValue(index, i)"></i>  
                    </div>  
                </el-form-item>
                <!-- 属性表格 -->
                <el-table v-if="formData.goods_specs.length" :data="formData.goods_specs" border style="width: 100%" height="265">
                    <el-table-column prop="attribute_specs" label="属性值">
                        <template slot-scope="scope">                                        
                            <label>{{Object.values(scope.row.attribute_specs).join(',')}}</label>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sales_price" label="销售价">
                        <template slot-scope="scope">
                            <el-input @input="onPriceInput(scope.row.sales_price)"  size="mini" v-model="scope.row.sales_price"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="活动价">
                        <template slot-scope="scope">
                            <el-input @input="onPriceInput(scope.row.price)"  size="mini" v-model="scope.row.price"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="inventory" label="库存">
                        <template slot-scope="scope">
                            <el-input @input="onIntegerInput(scope.row.inventory)"  size="mini" v-model="scope.row.inventory"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
            <!-- 其他设置 -->
            <el-card class="form-card">
                <div slot="header" class="add-title">其他设置</div>
                <el-form-item label="新品" prop="new">
                    <el-radio v-model="formData.new" :label="0">否</el-radio>
                    <el-radio v-model="formData.new" :label="1">是</el-radio>
                </el-form-item>
            </el-card>
            <!-- 详情内容 -->
            <el-card class="form-card">
                <div slot="header" class="add-title">详情内容</div>
                <quill-editor v-model="formData.body" :options="editorOption" ref="myQuillEditor">
                </quill-editor>
            </el-card>
        </el-form>
        <!-- 操作 -->
        <div class="add-buttom _display_flex">
            <el-button type="success" @click="validateForm">发布</el-button>
            <el-button type="info" @click="resetForm">重置</el-button>
        </div>
    </section>
</template>

<script>
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],

    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction

    [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],

    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image', 'video'],
    ['clean']                                         // remove formatting button
]
export default {
    name: 'GoodsDetails',
    title: '新增商品',
    computed: {
    },
    methods: {
        // 销售价 活动价
        onPriceInput(value, type) {
            let rule = /^[0-9]+(.[0-9]+)?$/
            if(!rule.test(Number(value))){
                this.formData[type] = null
                this.$message.warning('请输入有效价格')
            }
        },
        // 库存
        onIntegerInput(value) {
            let rule = /^[1-9]\d*$/
            if(!rule.test(value)){
                this.formData.inventory = null
                this.$message.warning('请输入合理库存')
            }
        },
        // 折扣
        onDiscountInput(value) {
            let rule = /^[1-9]$/
            if(!rule.test(Number(value))){
                this.$message.warning('请输入有效的折扣')
                this.formData.discount = 1
            }
            this.formData.price = Math.floor((this.formData.sales_price * this.formData.discount / 10) * 100) / 100
        },
        // 添加品牌
        addBrand() {
            this.$AddBrand({
                show: true,
                callback: (data) => {
                    this.brandOption.push({
                        label: data.name,
                        value: data.id
                    })
                    this.formData.brand_id = data.id
                }
            })
        },
        // 品牌列表
        async getBrandList() {
            const res = await this.$Http.getBrandList()
            if(res){
                this.brandOption = res.rows.map(v => {
                    return {
                        label: v.name,
                        value: v.id
                    }
                })
            }
        },
        // 添加分类
        addCategory() {
            const option = {
                show: true,
                callback: (data) => {
                    if(this.formData.category_id.length){
                        let pid = this.formData.category_id[0]
                        this.categoryOption = this.categoryOption.map(val => {
                            if(val.id == pid){
                                val.children = []
                                val.children.push(data)
                            }
                            return val
                        })
                    }else{
                        this.categoryOption.push(data)
                    }
                    this.formData.category_id.push(data.id)
                }
            }
            if(this.formData.category_id.length) {
                let pid = this.formData.category_id[0]
                option.pid = pid
                let pname = this.categoryOption.filter(v => v.id == pid)[0].name
                option.pname = pname
                option.rank = '一级'
            }
            this.$AddCategory(option)
        },
        // 分类列表
        async getCategoryList() {
            const res = await this.$Http.getCategoryList()
            if(res){
                this.categoryOption = res.rows
            }
        },
        // 缩略图上传图片
        handleUpload() {
            this.$Upload({
                show: true,
                leng: 1,
                callback: (data) => {
                    this.formData.img =  data[0]
                }
            })
        },
        // 轮播图上传成功
        handleSwitchSuccess(index) {
            this.switchImageIndex = index
            this.$Upload({
                show: true,
                leng: 1,
                callback: (data) => {
                    this.switchImageUrlArr[this.switchImageIndex].img_path = data[0]
                    this.formData.imgs.splice(this.switchImageIndex, 0, data[0])
                }
            })
        },
        // 轮播图删除
        handleSwitchRemove(index) {
            this.switchImageUrlArr[index].img_path = null
            this.formData.imgs.splice(index, 1)
        },
        // 添加属性
        addAttribute() {
            if(!this.attributeName) {
                this.$message.success('请输入属性');
                return false
            }
            let arr = this.formData.attributeList.filter(v => v.name === this.attributeName)
            if(arr.length) {
                this.$message.success('属性名称已存在');
                return false
            }
            this.formData.attributeList.push({
                name: this.attributeName,
                value: '',
                children: []
            })
            this.attributeName = null
        },
        // 删除属性
        delAttribute(index) {
            this.formData.attributeList.splice(index, 1)
        },
        // 添加属性值
        addAttributeValue(index) {
            let arr = this.formData.attributeList[index].children.filter(v => v == this.formData.attributeList[index].value)
            if(arr.length) {
                this.$message.success('属性值已存在');
                return false
            }
            this.formData.attributeList[index].children.push(this.formData.attributeList[index].value)
            this.formData.attributeList[index].value = ''
            this.formData.goods_specs = this.getAttributeTableData()
        },
        // 删除属性值
        delAttributeValue(index, i){
            // 删除属性值
            this.formData.attributeList[index].children.splice(i, 1)
            this.formData.goods_specs = this.getAttributeTableData()
        },
        // 获取属性值数据
        getAttributeTableData() {
            // 表格初始数据
            let obj = { attribute_specs: {}, sales_price: '', price: '', inventory: ''}
            // 储存属性值数据
            let array = []
            let attributeList = this.$Utli.deepCopy(this.formData.attributeList)
            attributeList.forEach(value => {
                if(!(value.name in obj.attribute_specs)){
                    obj.attribute_specs[value.name] = ''
                }
                value.children.forEach(val => {
                    if(array.length){
                        array.forEach(v => {
                            // 如果不存在属性值就赋值,则新加一条
                            if(v.attribute_specs[value.name]) {
                                obj = this.$Utli.deepCopy(v)
                                obj.attribute_specs[value.name] = val;
                                array.push(this.$Utli.deepCopy(obj))
                            }else{
                                v.attribute_specs[value.name] = val;
                            }
                        })
                    }else{                        
                        obj.attribute_specs[value.name] = val;
                        obj.sales_price = this.formData.sales_price
                        obj.price = this.formData.price
                        obj.inventory = this.formData.inventory
                        array.push(obj)
                    }
                })
            })
            // // 去重
            let deWeightArr = []
            array.forEach(val => {
                let arr = deWeightArr.filter( v => {
                    if(!v) return []
                    let isExist = true
                    for(let k in v.attribute_specs){
                        if(v.attribute_specs[k] !== val.attribute_specs[k]){
                            isExist = false
                        }
                    }
                    return isExist
                })
                if(!arr.length) {
                    deWeightArr.push(val)
                }
            })
            return deWeightArr
        },
        // 重置
        resetForm() {
            this.switchImageUrlArr = []
            this.formData.attributeList = []
            this.formData.body = null
            this.$refs.myQuillEditor.$refs.editor.firstChild.innerHTML = null
            this.$refs['ruleForm'].resetFields();
        },
        // 发布
        validateForm() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    this.submitForm()
                } else {
                    return false;
                }
            });
        },
        // 商品详情
        async getGoodsDetails() {
            let data = { 
                id: this.$route.params.id
            }
            let res = await this.$Http.getGoodsDetails({ data })
            if(res) {
                this.switchImageUrlArr = this.switchImageUrlArr.map((v, i) => {
                    if(res.imgs[i]){
                        v = res.imgs[i]
                    }
                    return v
                })
                res.attributeList = res.attributeList.map( v => {
                    v.value = ''
                    v.children = v.children.map(val => val.value)
                    return v
                })
                res.imgs = res.imgs.map(v => v.img_path)
                this.formData = res
                this.formData.id = this.$route.params.id
                this.formData.category_id = this.formData.category_id.map(v => Number(v))
            }
        },
        // 发布商品
        async submitForm() {
            let data = this.formData
            if (!data.attributeList.length) {
                this.$message('请输入属性')
                return false
            }
            if (!data.goods_specs.length) {
                this.$message('请输入属性值')
                return false
            }
            if(!data.body){
                this.$message('详情不能为空！')
                return false
            }
            let res = await this.$Http.getGoodsAddRedact({data})
            if(res) {
                setTimeout(() => {
                    this.$router.push({
                        path: '/goods/list'
                    })
                }, 1000)
            }
        }

    },
    data() {
        return {
            switchImageIndex: 0,                    // 轮播图下标
            switchImageUrlArr: [                    // 轮播图列表
                {img_path: ''},
                {img_path: ''},
                {img_path: ''},
                {img_path: ''},
                {img_path: ''} 
            ],
            brandOption: [],                        // 品牌数据
            categoryOption: [],                     // 分类数据
            categoryProps: {
                value: 'id',
                label: 'name',
                checkStrictly: true
            },
            attributeName: '',                      // 属性名称
            editorOption: {                         // 富文本           
                modules: {
                    toolbar: {
                        container: toolbarOptions,  // 工具栏
                        handlers: {
                            'image': () => {
                                this.$Upload({
                                    show: true,
                                    callback: (data) => {
                                        // 获取富文本组件实例
                                        this.$nextTick(() => {
                                            let quill = this.$refs.myQuillEditor.quill
                                            // 如果上传成功
                                            // 获取光标所在位置
                                            let length = quill.getSelection()?quill.getSelection().index : 0;
                                            // 插入图片，res为服务器返回的图片链接地址
                                            data.forEach(v => {
                                                quill.insertEmbed(length, 'image', this.path + v)
                                                // 调整光标到最后
                                                quill.setSelection(length + 1)
                                            })
                                        })
                                    }
                                })
                            }
                        }
                    }
                }
            },
            formData: {                             // 表单数据
                title: '',                          // 标题
                brand_id: '',                       // 品牌id
                category_id: [],                    // 分类id
                img: '',                            // 缩略图
                imgs: [],                           // 轮播图
                new: 0,                             // 是否新品
                sales_price: '',                    // 销售价
                price: '',                          // 活动价
                inventory: '',                      // 库存
                discount: '',                       // 折扣
                serial_number: '',                  // 编号
                attributeList: [],                  // 属性列表
                goods_specs: [],                    // 商品属性组合
                body: '',                           // 详情
            },
            rules: {
                title: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                ],
                brand_id: [
                    { required: true, message: '请选择商品品牌', trigger: 'blur' }
                ],
                category_id: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ],
                img: [
                    { required: true, message: '请选择缩略图', trigger: 'blur' }
                ],
                new: [
                    { required: true, message: '请选择新品', trigger: 'blur' }
                ],
                imgs: [
                    { required: true, message: '请选择轮播图', trigger: 'blur' }
                ],
                sales_price: [
                    { required: true, message: '请输入销售价', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入活动价', trigger: 'blur' }
                ],
                inventory: [
                    { required: true, message: '请输入库存', trigger: 'blur' }
                ],
                serial_number: [
                    { required: true, message: '请输入编号', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
    },
    mounted() {
        let route = this.$route
        // 编辑加载
        if(route.path === `/goods/compile/${route.params.id}`) {
            // 加载商品详情
            this.getGoodsDetails()
        }
        // 加载商品品牌
        this.getBrandList()
        // 加载商品分类
        this.getCategoryList()
    }
}
</script>

<style lang="scss" scoped>
    .goods-add-box{
        width: 100%;
        .form-card{
            margin-bottom: 20px;
        }
        .form-item-w{
            width: 200px;
            margin-right: 20px;
        }
        .form-item-value{
            margin-right: 20px;
            margin-top: 10px;
            .item-value-icon{
                font-size: $font-size-lx;
                cursor: pointer;
            }
        }
        .form-item-label{
            &::before{
                content: '*';
                color: #F56C6C;
                margin-right: 4px;
            }
        }
    }
    .upload-box{
        .upload-item{
            margin-right: 10px;
            flex-direction: column;
        }
        .upload-tab{
            font-size: $font-size-xs;
            color: $text-color-grey;
        }
        .avatar-uploader{
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            justify-content: center;
            &:hover {
                border-color: #409EFF;
            }
            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                text-align: center;
            }
        }
        .avatar {
            width: 100px;
            height: 100px;
            line-height: 100px;
        }
    }
    .upload-del{
        position: absolute;
        top: 0;
        left: 0;
        justify-content: center;
        background: rgba(0, 0, 0, 0.5);
        i{
            font-size: 28px;
            color: #fff;
            text-align: center;
        }
    }
    .add-buttom{
        width: 100%;
        justify-content: center;
    }
    /deep/.ql-editor{
        height:400px;
    }
    .ql-snow .ql-tooltip{
        left: 100px; 
    }
</style>